import React, { useState, useEffect } from 'react'
import { Animated, View, Text, TextInput, TextStyle, ViewStyle, StyleProp, StyleSheet, TouchableWithoutFeedback } from 'react-native';
import { FieldRefType } from '../types'
import Icon from '../Icon'
import renderNode from '../helpers/renderNode'
/**
 * todo 要怎么定义字体大小？
 */
type Props = React.ComponentPropsWithRef<typeof TextInput> & {

  type?: string,
  disabled?: boolean;
  disabledInputStyle?: StyleProp<TextStyle>;
  label?: string;
  // todo 字体大小 这个字段是否需要 我认为label只需要简单提供就好了 所以不用太精细
  labelFontSize?: number,
  labelStyle?: StyleProp<ViewStyle>;
  value: string;
  onChangeText?: (query: string) => void;
  inputStyle?: StyleProp<TextStyle>;
  style?: StyleProp<ViewStyle>;
  rightIcon?: string | React.ReactElement<{}>
  onRightIconClick?: () => void;
  // 是否启用清除图标
  clearable?: boolean;
}
type TextInputHandles = FieldRefType
const Field = React.forwardRef<TextInputHandles, Props>(({
  onChangeText,
  onRightIconClick,
  clearable,
  value,
  style,
  type,
  ...rest
}: Props, ref) => {
  /**
   * 传递ref节点添加方法
   */
  const root = React.useRef<TextInput>(null);
  React.useImperativeHandle(ref, () => {
    const input = root.current;
    if (input) {
      return {
        focus: () => input.focus(),
        clear: () => input.clear(),
        // setNativeProps: (args: TextInputProps) => input.setNativeProps(args),
        isFocused: () => input.isFocused(),
        blur: () => input.blur(),
      };
    }
    const noop = () => {
      throw new Error('TextInput is not available');
    };
    return {
      focus: noop,
      clear: noop,
      blur: noop,
      isFocused: noop
    };
  });
  /**
   * todo 暂时这样吧，后面要补点击的
   */
  const clearableHandel = () => {
    root.current?.clear()
  }
  /**
   * [Props]type
   * 输入框形态
   * 软键盘形态
   */
  const keyboardType = type === 'number' ? 'numeric' :'default'
  const [encryption, setEncryption] = useState<boolean>(false)
  useEffect(() => {
    if (type === 'password') {
      setEncryption(true)
    } else {
      setEncryption(false)
    }
  }, [type])
  return (
    <Animated.View>
      <View style={styles.container}>
        {rest.label && (
          <View style={[{ paddingRight: 8 }, rest.labelStyle]}>
            <Text style={{ fontSize: rest.labelFontSize || 16 }}>{rest.label}：</Text>
          </View>)
        }
        <View style={styles.inputMain}>
          <TextInput
            ref={root}
            style={StyleSheet.flatten([
              styles.input,
              rest.inputStyle,
              rest.disabled && styles.disabledInput,
              rest.disabled && rest.disabledInputStyle,
              rest.multiline && styles.textarea,
              style
            ])}
            underlineColorAndroid="transparent"
            editable={!rest.disabled}
            secureTextEntry={encryption}
            keyboardType={keyboardType}
            {...rest}
          />
          {clearable && (
            <Text style={{ paddingRight: 8 }} onPress={clearableHandel}>
              <Icon name="closecircle" color="#333"></Icon>
            </Text>
          )}
        </View>
        {rest.rightIcon && (
          <TouchableWithoutFeedback onPress={onRightIconClick}>
            <View style={{ paddingLeft: 8 }}>{renderNode(Icon, rest.rightIcon)}</View>
          </TouchableWithoutFeedback>)
        }
      </View>
    </Animated.View>
  )
})

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 8,
    backgroundColor: '#fff',
  },
  inputMain: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  input: {
    flex: 1,
    fontSize: 18,
    minWidth: 0,
    minHeight: 40,
    paddingLeft: 8,
    paddingRight: 8,
  },
  textarea: {
    minHeight: 80,
    textAlignVertical: 'top'
  },
  disabledInput: {
    opacity: 0.5,
  },
});

export default Field